package cn.imvc.app.controllers;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.imvc.app.domains.Constants;
import cn.imvc.app.entities.Member;
import cn.imvc.app.models.MemberModel;
import cn.imvc.core.ICache;
import cn.imvc.core.Render;
import cn.imvc.util.Md5;
import cn.imvc.util.SMSVerification;
import cn.imvc.util.ToolUtils;

@Controller
@RequestMapping("/member")
public class MemberControllerImpl implements MemberController {

	private Logger logger = Logger.getLogger(MemberControllerImpl.class);

	@Autowired
	MemberModel memberModel;

	@Autowired
	ICache cache;

	@Autowired
	SMSVerification smsVerification;

	@RequestMapping("/register.html")
	public String register(Model model, HttpServletRequest request) {
		model.addAttribute("key1", Md5.encode(String.valueOf(System.currentTimeMillis())));
		String ip = ToolUtils.getIpAddress(request);
		Integer ipTimes = cache.get(Constants.CACHENAME_MEMBER, "IP_TIMES_" + ip);
		if(ipTimes != null && ipTimes >= smsVerification.getIpTimes()){
			model.addAttribute("showImageCode", true);
		} else {
			model.addAttribute("showImageCode", false);
		}
		return "member/register";
	}

	@RequestMapping("/sendCode.html")
	@ResponseBody
	public String sendCode(String loginname, String imagecode, HttpServletRequest request) {
		String ip = ToolUtils.getIpAddress(request);
		String key = request.getSession().getId();
		Map<String, String> map = memberModel.sendCode(loginname, imagecode, ip, key);
		return Render.json(map);
	}

	@RequestMapping("/sendCodeByMobile.html")
	@ResponseBody
	public String sendCodeByMobile(String loginname, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		// 防止短信攻击
		Member member = memberModel.getByLoginname(loginname);
		if(member == null){
			map.put("code", "0");
			map.put("msg", "系统异常，请稍后再试");
		} else {
			map = memberModel.sendMessageCode(loginname);
		}
		return Render.json(map);
	}

	@RequestMapping("/registersubmit.html")
	@ResponseBody
	public String registersubmit(Member register, String messagecode, String domain, HttpServletRequest request) {
		String serverName = request.getServerName();
		Map<String, String> map = memberModel.saveRegister(register, messagecode, domain, serverName);
		return Render.json(map);
	}

	@RequestMapping("/registersubmit.htm")
	@ResponseBody
	public String pcregistersubmit(Member register, String messagecode, String imagecode, HttpServletRequest request) {
		String serverName = request.getServerName();
		HttpSession session = request.getSession();
		Map<String, String> map = memberModel.savePcRegister(register, messagecode, imagecode, serverName, session.getId());
		return Render.json(map);
	}

	@RequestMapping("/login.html")
	public String login() {
		return "member/login";
	}

	@RequestMapping("/checkLoginname.html")
	@ResponseBody
	public String checkLoginname(String loginname) {
		Map<String, String> result = memberModel.checkLoginname(loginname);
		return Render.json(result);
	}

	@RequestMapping("/loginsubmit.html")
	@ResponseBody
	public String loginsubmit(Member member) {
		Map<String, Object> result = memberModel.checkLoginSubmit(member);
		return Render.json(result);
	}

	@RequestMapping("/find.html")
	public String find() {
		return "member/find";
	}

	@RequestMapping("/findfirst.html")
	public String findfirst(Model model, HttpServletRequest request) {
		String ip = ToolUtils.getIpAddress(request);
		Integer ipTimes = cache.get(Constants.CACHENAME_MEMBER, "IP_TIMES_" + ip);
		if(ipTimes != null && ipTimes >= smsVerification.getIpTimes()){
			model.addAttribute("showImageCode", true);
		} else {
			model.addAttribute("showImageCode", false);
		}
		return "member/findfirst";
	}

	@RequestMapping("/findsecond.html")
	@ResponseBody
	public String findsecond(String mobile, String messagecode) {
		Map<String, String> result = memberModel.checkMCodeForKey(mobile, messagecode);
		return Render.json(result);
	}
	
	@RequestMapping("/findthird.html")
	public String findthird(String key1, String loginname, Model model) {
		model.addAttribute("loginname", loginname);
		model.addAttribute("key1", key1);
		return "member/findthird";
	}

	@RequestMapping("/findsubmit.html")
	@ResponseBody
	public String findsubmit(String loginname, String passwd, String key1) {
		Map<String, String> result = memberModel.saveResetPasswd(loginname, passwd, key1);
		return Render.json(result);
	}

	@RequestMapping("/login.htm")
	public String pclogin() {
		return "member/pclogin";
	}

	@RequestMapping("/register.htm")
	public String pcregister(Model model, HttpServletRequest request) {
		model.addAttribute("key1", Md5.encode(String.valueOf(System.currentTimeMillis())));
		String ip = ToolUtils.getIpAddress(request);
		Integer ipTimes = cache.get(Constants.CACHENAME_MEMBER, "IP_TIMES_" + ip);
		if(ipTimes != null && ipTimes >= smsVerification.getIpTimes()){
			model.addAttribute("showImageCode", true);
		} else {
			model.addAttribute("showImageCode", false);
		}
		return "member/pcregister";
	}

	@RequestMapping("/checkRegisterLoginname.html")
	@ResponseBody
	public String checkRegisterLoginname(Model model, String loginname) {
		Map<String, String> result = memberModel.checkRegisterLoginname(loginname);
		return Render.json(result);
	}

	@RequestMapping("/getImageCode.htm")
	@ResponseBody 
	public String getImageCode(HttpServletRequest request, HttpServletResponse response) {
		String sessionId = request.getSession().getId();
		BufferedImage image = memberModel.getImageCode(sessionId);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			ImageIO.write(image, "png", out);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("获取随机码图片error，出错信息：", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					logger.error("获取随机码图片时关闭输出流error，出错信息：", e);
				}
			}
		}
		return null;
	}

	@RequestMapping("/find.htm")
	public String pcfind(Model model, HttpServletRequest request) {
		String ip = ToolUtils.getIpAddress(request);
		Integer ipTimes = cache.get(Constants.CACHENAME_MEMBER, "IP_TIMES_" + ip);
		if(ipTimes != null && ipTimes >= smsVerification.getIpTimes()){
			model.addAttribute("showImageCode", true);
		} else {
			model.addAttribute("showImageCode", false);
		}
		return "member/pcfind";
	}

	@RequestMapping("/findthird.htm")
	public String pcfindthird(Model model, String loginname, String key1) {
		model.addAttribute("loginname", loginname);
		model.addAttribute("key1", key1);
		return "member/pcfindthird";
	}

	@RequestMapping("/checkTokenForApp.html")
	@ResponseBody
	public String checkTokenForApp(Model model, String token, String app) {
		memberModel.checkTokenForApp(token, app);
		return null;
	}

}
